package com.powerbank.paymentcenter.mq.consumer;

import com.powerbank.common.event.user.UserRegisteredEvent;
import com.powerbank.paymentcenter.service.WalletService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * 用户注册事件消费者
 * 处理新用户注册后的钱包创建
 */
@Slf4j
@Component
@RocketMQMessageListener(
    topic = "PowerBank-User-Topic",
    selectorExpression = "USER_REGISTERED",
    consumerGroup = "payment-center-user-consumer"
)
public class UserRegisteredConsumer implements RocketMQListener<UserRegisteredEvent> {

    @Autowired
    private WalletService walletService;

    @Override
    public void onMessage(UserRegisteredEvent event) {
        try {
            log.info("收到用户注册事件: userId={}, phone={}, registerChannel={}", 
                    event.getUserId(), event.getPhone(), event.getRegisterChannel());

            // 为新用户创建钱包
            walletService.createWallet(event.getUserId());
            
            // 新用户注册奖励
            BigDecimal rewardAmount = new BigDecimal("10.00");
            walletService.recharge(
                event.getUserId(), 
                rewardAmount, 
                "新用户注册奖励", 
                "SYSTEM_REWARD"
            );
            
            // 如果有邀请码，给邀请人奖励
            if (event.getInviteCode() != null) {
                // 这里可以调用用户中心获取邀请人信息，然后给邀请人奖励
                log.info("用户使用邀请码注册: userId={}, inviteCode={}", 
                        event.getUserId(), event.getInviteCode());
            }
            
            log.info("新用户钱包创建成功: userId={}, rewardAmount={}", 
                    event.getUserId(), rewardAmount);

        } catch (Exception e) {
            log.error("处理用户注册事件失败: userId={}", event.getUserId(), e);
            throw new RuntimeException("用户注册事件处理失败", e);
        }
    }
}